/*
 * Copyright 2016 Wealth Inc. All rights reserved.
 */
 package com.wealth.commodity.service.impl;

import java.util.Date;

import org.apache.commons.lang.RandomStringUtils;
import org.apache.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import com.wealth.commodity.entity.GoodsVirtual;
import com.wealth.commodity.repository.GoodsVirtualDao;
import com.wealth.commodity.service.IGoodsVirtualService;
import com.wealth.coupon.util.LabelFileEncrypt;

import iaas.enums.StatusEnum;
import iaas.service.impl.BaseServiceImpl;

/**
 * @author chan
 */
@Component
public class GoodsVirtualServiceImpl extends BaseServiceImpl<GoodsVirtual> implements IGoodsVirtualService{

	Logger logger = Logger.getLogger(GoodsVirtualServiceImpl.class);
	
	@Autowired
	private GoodsVirtualDao goodsVirtualDao;
	
	/**
	 * 产生四位唯一标识 32机制的字符串
	 */
	private String generateUid() {
		String uid = RandomStringUtils.random(4, LabelFileEncrypt.BASE32);
		GoodsVirtual goodsVirtual = goodsVirtualDao.findByUid(uid);
		if(goodsVirtual==null){
			return uid;
		}else{
			return generateUid();
		}
	}

	@Override
	public GoodsVirtual saveGoodsVirtual(GoodsVirtual goodsVirtual) throws Exception {
		goodsVirtual.setCreateTime(new Date());
		goodsVirtual.setUid(generateUid());
		goodsVirtual.setStatus(StatusEnum.NORMAL.getValue());
		goodsVirtualDao.save(goodsVirtual);
		return goodsVirtual;
	}
	
	
	@Override
	public void updateGoodsVirtual(GoodsVirtual goodsVirtual) throws Exception {
		
		if(goodsVirtual.getId()!=null){
			//保存商品时，设置虚拟商品属性，再次编辑时
			GoodsVirtual temp =  goodsVirtualDao.findOne(goodsVirtual.getId());
			temp.setStartTime(goodsVirtual.getStartTime());
			temp.setEndTime(goodsVirtual.getEndTime());
			goodsVirtualDao.save(temp);
		}else{
			//保存商品时，没有设置虚拟商品属性，再次编辑时
			saveGoodsVirtual(goodsVirtual);
		}
		
	}

}
